package com.gzhryc.jdbc.utils;

import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

public class JsonTools {
	
	private static ObjectMapper readMapper;
	private static ObjectMapper writeMapper;
	
	static {
		readMapper = new ObjectMapper();
		readMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		readMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
		readMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
		
		writeMapper = new ObjectMapper();
		writeMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		//不输出NULL对象
		writeMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
		writeMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
	}
	
	public static<T> T fromJson(InputStream stream,Class<T> className){
		try {
			return readMapper.readValue(stream, className);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static<T> T fromJson(String strJson,Class<T> className){
		try {
			return readMapper.readValue(strJson, className);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public static Map<String,Object> fromJson(String strJson){
		try {
			return readMapper.readValue(strJson, Map.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String toJson(Object obj){
		try {
			return writeMapper.writeValueAsString(obj);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static List<?> str2List(String strJson){
		try {
			return readMapper.readValue(strJson, List.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}